//
// Created by wuzhe on 2022/3/31.
//

#ifndef UNIVERSEROOM_REACTOR_H
#define UNIVERSEROOM_REACTOR_H

#include <cstdlib>
#include <cstdio>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <ctime>
#include "Console.h"
#include "Space.hh"
#include "UniverseDatagram.hh"
#define MAX_EVENTS  1024
#define BUFLEN 1024
#define SERV_PORT   8080

namespace JJ {
/*
 * status:1表示在监听事件中，0表示不在
 * last_active:记录最后一次响应时间,做超时处理
 */
    struct myevent_s {
        int fd;                 //cfd listenfd
        int num;
        int events;             //EPOLLIN  EPLLOUT
        void *arg;              //指向自己结构体指针
        void (*recv_call_back)(int fd, int events, void *arg);
        void (*send_call_back)(int fd, int events, void *arg);
        int status;
        char readBuf[BUFLEN];
        char writeBuf[BUFLEN];
        int readLeftIndex;
        int readRightIndex;
        unsigned int writeLeftIndex;
        unsigned int writeRightIndex;
        long last_active;
        std::string ip;
        int kevent_num;
    };

    void processDatagram(ParseRes& datagram, myevent_s& event);
    void update();
    void processBuf(int i);

    void eventset(struct myevent_s *ev, int fd, bool recvFlag, void (*call_back)(int, int, void *), void *arg);
    void recvdata(int fd, int events, void *arg);
    void senddata(int fd, int events, void *arg);

    void eventadd(int efd, int events, struct myevent_s *ev);

    void eventdel(int efd, struct myevent_s *ev);
    // IP connect
    void acceptconn(int lfd, int, void *);

    void initlistensocket(int efd, short port);

    bool initclientsocket(int efd, short port);

    bool checkMagic(char c1[4]);

    std::list<ParseRes> parseDatagram(char *content, unsigned contentLen, int & lastIndex);

    bool sendDatagram(int num, UnivHead *head, const char *content);

    void playerDisconnect(int num);

}
#endif //UNIVERSEROOM_REACTOR_H
